"""  token操作方法包
@Project: Rebar
@File: access_token.py
@Author: hzc
@Date: 2023/3/21 16:58
"""
from datetime import datetime, timedelta
import jwt
from config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_REFRESH, ACCESS_TOKEN_EXPIRE_MINUTES


def create_payload(data: dict):
    """
    生成jwt的payload
    :param data:
    :return:
    """
    payload = data
    iat = datetime.utcnow()
    # print(datetime.timestamp(iat), datetime.timestamp(datetime.now()))
    exp = iat + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    payload.update({
        'iat': iat,
        # 'exp': exp  # 过期时间
    })
    return payload


def create_token(data: dict):
    """
    创建jwt
    :param data:
    :return:
    """
    payload = create_payload(data)
    token = jwt.encode(payload=payload, key=SECRET_KEY, algorithm=ALGORITHM)
    return token


def parse_token(token: str):
    """
    获取token的payload数据
    :param token:
    :return: payload (type: dict)
    """
    try:
        payload = jwt.decode(token, key=SECRET_KEY, algorithms=ALGORITHM)
        return payload
    except Exception as e:
        print("token解析异常, access_token.py文件")
        print(e, e.__traceback__.tb_lineno)
        return None


if __name__ == '__main__':
    my_token = create_token({'user_id': 1, "role_name": "系统管理员"})


